package com.mrd.gtimp.registered;

import com.mrd.constant.MsgConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.config.web.json.annotation.JField;
import com.mrd.framework.config.web.json.annotation.Json;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.entity.Dept;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.base.service.DeptBiz;
import com.mrd.gtimp.base.service.UserBiz;
import com.mrd.gtimp.business.entity.Attachment;
import com.mrd.gtimp.business.entity.HgData;
import com.mrd.gtimp.business.entity.RegisteredCompany;
import com.mrd.gtimp.business.entity.RegisteredCompanyAttachment;
import com.mrd.gtimp.business.entity.RegisteredPerson;
import com.mrd.gtimp.business.service.AttachmentBiz;
import com.mrd.gtimp.business.service.HgDataBiz;
import com.mrd.gtimp.business.service.RegisteredCompanyAttachmentBiz;
import com.mrd.gtimp.business.service.RegisteredCompanyBiz;
import com.mrd.gtimp.business.service.RegisteredPersonBiz;
import com.mrd.util.ChineseUtill;
import com.mrd.util.KeyGenerator;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

@Controller
@RequestMapping("/")
public class RegisteredAction {

    private static final long serialVersionUID = -3008237726668537183L;

    @Resource
    private UserBiz userBiz;

    @Resource
    private CompanyBiz companyBiz;

    @Resource
    private DeptBiz deptBiz;

    @Resource
    private HgDataBiz hgDataBiz;

    @Resource
    private RegisteredCompanyBiz registeredCompanyBiz;

    @Resource
    private RegisteredPersonBiz registeredPersonBiz;

    @Resource
    private AttachmentBiz attachmentBiz;

    private File attach;

    private String attachFileName;

    private String attachContentType;

    private String com_name;

    private String fax;

    private String com_address;

    private String com_code;

    private String com_customs_code;

    private String com_link_person;

    private String com_link_phone;

    private String customs_broker;

    private String customs_broker_id;

    private String com_email;

    private String com_type;

    private String service_port;

    private String service_port_code;

    private String[] contact_person;

    private String[] login_name;

    private String[] login_password;

    private String[] telephone;

    private String[] mobile_phone;

    private String[] mail;

    private String decode(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 客户公司注册页面
     */
    @RequestMapping("/reg-regPage")
    public String regPage() {
        return "/gtimp/registered/regPage";
    }

    /**
     * 报关公司注册页面
     */
    @RequestMapping("/reg-regDeclarationPage")
    public String regDeclarationPage() {
        return "/gtimp/registered/regDeclarationPage";
    }

    /**
     * 客户公司注册协议页面
     */
    @RequestMapping("/reg-agreement")
    public String agreement() {
        return "/gtimp/registered/regAgreement";
    }

    /**
     * 报关公司注册协议页面
     */
    @RequestMapping("/reg-declarationAgreement")
    public String declarationAgreement() {
        return "/gtimp/registered/regDeclarationAgreement";
    }

    /**
     * 选择注册公司的类型
     */
    @RequestMapping("/reg-selectRegistered")
    public String selectRegistered() {
        return "/gtimp/registered/regSelectRegistered";
    }

    /**
     * 查询口岸
     */
    @RequestMapping("/reg-findPort")
    @ResponseBody
    public Page<HgData> findPort(Jqgrid jqgrid) {
        Filter filters = jqgrid.getFilters();
        try {
            filters = new Filter();
            filters.addRule(new SearchRule("type", SearchRuleOption.eq, "HGD_2"));
            Pageable page = new PageRequest(0, Integer.MAX_VALUE, new Sort("code"));
            jqgrid = new Jqgrid(filters, page);
            Page<HgData> hgDatas = hgDataBiz.findByJqgrid(jqgrid);
            return hgDatas;
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/reg-checkUnique")
    @ResponseBody
    public String checkUnique() {
        Result msg;
        String name = HttpUtils.getRequest().getParameter("name");
        if (StringUtils.isNotEmpty(name)) {
            String hql = " from com.mrd.gtimp.business.entity.RegisteredPerson registeredPerson where registeredPerson.login_name='"
                    + name + "' ";
            List<RegisteredPerson> registeredPersons = registeredPersonBiz
                    .findEntityByHql(hql, 0, 0, null);
            if (registeredPersons != null && registeredPersons.size() > 0) {
                msg = Result.newFailInstance(MsgConstants.CHECK_IS_EXIST);
            } else {
                msg = Result.newSuccessInstance(MsgConstants.CHECK_NOT_EXIST);
            }
        }
        return null;
    }

    /**
     * 检查注册公司是否注册
     */
    @RequestMapping("/reg-checkRegCompanyExist")
    @ResponseBody
    public Result checkRegCompanyExist(String com_name, String com_type) {
        Result msg = null;
        if (StringUtils.isNotEmpty(com_name)) {
            String hql = "from com.mrd.gtimp.business.entity.RegisteredCompany rc where rc.com_name='"
                    + com_name
                    + "' and (rc.approve_status = '0' or rc.platform_approve_status = '0') "
                    + " and (rc.platform_approve_status is null or rc.platform_approve_status = '0')"
                    + " and rc.com_type='" + com_type +"'";
            List<RegisteredCompany> registeredCompanies = registeredCompanyBiz
                    .findEntityByHql(hql, 0, 0, null);
            if (registeredCompanies != null && registeredCompanies.size() > 0) {
                msg = Result.newFailInstance(MsgConstants.COMPANY_IS_EXIST);
            } else {
                msg = Result.newSuccessInstance(MsgConstants.COMPANY_NOT_EXIST);
            }
        }
        return msg;
    }

    @Resource
    RegisteredCompanyAttachmentBiz registeredCompanyAttachmentBiz;

    /**
     * 客户注册方法
     */
    @RequestMapping("/reg-doRegistered")
    public ModelAndView doRegistered(Attachment attachment, String com_name, String fax,
                                     String com_address, String com_code, String com_customs_code, String com_link_person,
                                     String com_link_phone, String com_email, String customs_broker, String customs_broker_id,
                                     String bill_no) {

        Result msg = null;
        try {
            com_name = ChineseUtill.toChinese(com_name);
            fax = ChineseUtill.toChinese(fax);
            com_address = ChineseUtill.toChinese(com_address);
            com_link_person = ChineseUtill.toChinese(com_link_person);
            customs_broker = ChineseUtill.toChinese(customs_broker);
            service_port = ChineseUtill.toChinese(service_port);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        if (StringUtils.isNotEmpty(com_name)) {
            try {
                RegisteredCompany company = new RegisteredCompany();
                company.setReg_company_id(null);
                company.setCom_name(com_name);
                company.setFax(fax);
                company.setCom_address(com_address);
                company.setCom_code(com_code);
                company.setCom_customs_code(com_customs_code);
                company.setCom_link_person(com_link_person);
                company.setCom_link_phone(com_link_phone);
                company.setCom_email(com_email);
                company.setCustoms_broker(customs_broker);
                company.setCustoms_broker_id(customs_broker_id);
                company.setCom_type("CL");
                company.setReg_time(new Date());
                registeredCompanyBiz.saveOrupdateEntity(company);
                Filter filters = new Filter();
                filters.addRule(new SearchRule("bill_no", SearchRuleOption.eq, bill_no));
                List<RegisteredCompanyAttachment> attachments = registeredCompanyAttachmentBiz
                        .findEntityByFilter(0, 10, filters, null);
                for (RegisteredCompanyAttachment attachment1 : attachments) {
                    attachment1.setRegisteredCompany(company);
                    attachment1.setBill_no(company.getReg_company_id());
                    registeredCompanyAttachmentBiz.saveOrupdateEntity(attachment1);
                }
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);

            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            }
        }
        Map model = new HashedMap();
        model.put("msg", msg);
        return new ModelAndView("/gtimp/registered/regSuccess", model);
    }

    /**
     * 报关注册方法
     */
    @RequestMapping("/reg-doDeclarationRegistered")
    @ResponseBody
    public ModelAndView doDeclarationRegistered(Attachment attachment, String com_name, String fax,
                                                String com_address, String com_code, String com_customs_code, String com_link_person,
                                                String com_link_phone, String com_email, String customs_broker, String customs_broker_id,
                                                String bill_no, String service_port, String service_port_code) {
        Result msg = null;
        try {
            com_name = ChineseUtill.toChinese(com_name);
            fax = ChineseUtill.toChinese(fax);
            com_address = ChineseUtill.toChinese(com_address);
            com_link_person = ChineseUtill.toChinese(com_link_person);
            customs_broker = ChineseUtill.toChinese(customs_broker);
            service_port = ChineseUtill.toChinese(service_port);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
        }
        if (StringUtils.isNotEmpty(com_name)) {
            try {
                RegisteredCompany company = new RegisteredCompany();
                company.setReg_company_id(null);
                company.setCom_name(com_name);
                company.setFax(fax);
                company.setCom_address(com_address);
                company.setCom_code(com_code);
                company.setCom_customs_code(com_customs_code);
                company.setCom_link_person(com_link_person);
                company.setCom_link_phone(com_link_phone);
                company.setCom_email(com_email);
                company.setCustoms_broker(customs_broker);
                company.setCustoms_broker_id(customs_broker_id);
                company.setService_port(service_port.substring(service_port.indexOf(") ") + 1));
                company.setService_port(company.getService_port().trim());
                company.setService_port_code(service_port_code);
                company.setCom_type("CC");
                company.setReg_time(new Date());
                registeredCompanyBiz.saveOrupdateEntity(company);
                Filter filters = new Filter();
                filters.addRule(new SearchRule("bill_no", SearchRuleOption.eq, bill_no));
                List<RegisteredCompanyAttachment> attachments = registeredCompanyAttachmentBiz
                        .findEntityByFilter(0, 10, filters, null);
                for (RegisteredCompanyAttachment attachment1 : attachments) {
                    attachment1.setRegisteredCompany(company);
                    attachment1.setBill_no(company.getReg_company_id());
                    registeredCompanyAttachmentBiz.saveOrupdateEntity(attachment1);
                }
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);

            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            }
        }
        Map model = new HashedMap();
        model.put("msg", msg);
        return new ModelAndView("/gtimp/registered/regSuccess", model);
    }

    @RequestMapping("/reg-upload")
    private void upload(RegisteredCompany company, Attachment attachment) {
        if (null != attach) {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int date = calendar.get(Calendar.DATE);
            // ServletContext context = ServletActionContext.getServletContext();
            ServletContext context = HttpUtils.getServletContext();
            String suffix = getAttachFileName().substring(getAttachFileName().lastIndexOf(".")); // 后缀名
            String dataDir = context.getRealPath("/WEB-INF"); // 服务器路径
            String filePath = year + "\\" + month + "\\" + date; // 保存上传文件的文件夹路径
            FileInputStream is = null;
            FileOutputStream os = null;
            try {
                File file = new File(dataDir + "\\" + filePath);
                if (file.exists() == false) {
                    file.mkdirs();
                }
                String key = KeyGenerator.getKey("reg_");

                String savePath = dataDir + "\\" + filePath + "\\" + key + suffix;
                is = new FileInputStream(attach);
                os = new FileOutputStream(savePath);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) > 0) {
                    os.write(buffer, 0, len);
                }
                attachment = new Attachment();
                attachment.setId(null);
                attachment.setCtime(new Date());
                attachment.setName(getAttachFileName());
                attachment.setReplacename(key);
                attachment.setPath("\\WEB-INF\\" + filePath + "\\" + key + suffix);
                // attachment.setCREATOR(user.getId());
                attachmentBiz.saveOrupdateEntity(attachment);
                List<String> properties = new ArrayList<String>();
                properties.add("so_file_id");
                company.setSo_file_id(attachment.getId());
                registeredCompanyBiz.updateEntity(company, properties);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                close(is, os);
            }
        }
    }

    /**
     * 注册页面获取报关公司
     */
    @RequestMapping("/reg-declaraCompany")
    @ResponseBody
    @Json({@JField("declaration_company_id"), @JField("com_customs_code"),
            @JField("declaration_company")})
    public String[][] declaraCompany(Jqgrid jqgrid) {
        jqgrid.addRule(new SearchRule("type", SearchRuleOption.eq, "CC"));
        jqgrid.addRule(new SearchRule("isabled", SearchRuleOption.eq, "0"));
        jqgrid.addRule(new SearchRule("state", SearchRuleOption.eq, "0"));
        try {
            jqgrid.addOrder(Sort.Direction.ASC, "name");
            jqgrid.setSize(200);
            Page<Company> companies = companyBiz.findByJqgrid(jqgrid);
            List<Company> companyList = companies.getContent();
            String[][] results = new String[companyList.size()][3];
            for (int i = 0; i < results.length; i++) {
                Company c = companyList.get(i);
                results[i][0] = c.getName();
                results[i][1] = c.getId();
                results[i][2] = c.getCom_customs_code();
            }
            return results;
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 激活用户账号
     */
    @RequestMapping("/reg-activateAccount")
    public ModelAndView activateAccount() {
        Result msg;
        String userId = HttpUtils.getRequest().getParameter("activate");
        String deptId = "";
        String companyId = "";
        User user = null;
        Dept dept = null;
        Company company = null;
        List<String> properties = null;
        if (StringUtils.isNotEmpty(userId)) {
            try {
                user = userBiz.findEntityById(userId);
                if (user != null) {
                    if ("0".equals(user.getIsabled())) {// 激活
                        msg = Result.newFailInstance(MsgConstants.ACCOUNT_IS_ACTIVATE);
                    } else if ("1".equals(user.getIsabled())) {// 未激活
                        deptId = user.getDepts().get(0).getId();
                        dept = deptBiz.findEntityById(deptId);
                        companyId = dept.getCompany().getId();
                        company = companyBiz.findEntityById(companyId);
                        properties = new ArrayList<String>();
                        properties.add("isabled");
                        user.setIsabled("0");
                        userBiz.updateEntity(user, properties);
                        properties = new ArrayList<String>();
                        properties.add("isabled");
                        dept.setIsabled("0");
                        deptBiz.updateEntity(dept, properties);
                        properties = new ArrayList<String>();
                        properties.add("isabled");
                        company.setIsabled("0");
                        companyBiz.updateEntity(company, properties);
                        msg = Result.newSuccessInstance(MsgConstants.ACCOUNT_ACTIVATE_SUCCESS);
                        Map model = new HashedMap();
                        model.put("msg", msg);
                        return new ModelAndView("/gtimp/registered/activateAccount", model);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Map model = new HashedMap();
        model.put("msg", Result.newSuccessInstance(MsgConstants.ACCOUNT_IS_ACTIVATE));
        return new ModelAndView("/gtimp/registered/activateAccount", model);
    }

    private void close(InputStream is, OutputStream os) {
        try {
            if (null != is) {
                is.close();
            }
            if (null != os) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getCom_name() {
        return com_name;
    }

    public void setCom_name(String com_name) {
        this.com_name = com_name;
    }

    public String getFax() {
        return fax;
    }

    public void setFax(String fax) {
        this.fax = fax;
    }

    public String getCom_address() {
        return com_address;
    }

    public void setCom_address(String com_address) {
        this.com_address = com_address;
    }

    public String[] getContact_person() {
        return contact_person;
    }

    public void setContact_person(String[] contact_person) {
        this.contact_person = contact_person;
    }

    public String[] getLogin_name() {
        return login_name;
    }

    public void setLogin_name(String[] login_name) {
        this.login_name = login_name;
    }

    public String[] getLogin_password() {
        return login_password;
    }

    public void setLogin_password(String[] login_password) {
        this.login_password = login_password;
    }

    public String[] getTelephone() {
        return telephone;
    }

    public void setTelephone(String[] telephone) {
        this.telephone = telephone;
    }

    public String[] getMobile_phone() {
        return mobile_phone;
    }

    public void setMobile_phone(String[] mobile_phone) {
        this.mobile_phone = mobile_phone;
    }

    public String[] getMail() {
        return mail;
    }

    public void setMail(String[] mail) {
        this.mail = mail;
    }

    public File getAttach() {
        return attach;
    }

    public void setAttach(File attach) {
        this.attach = attach;
    }

    public String getAttachFileName() {
        return attachFileName;
    }

    public void setAttachFileName(String attachFileName) {
        this.attachFileName = attachFileName;
    }

    public String getAttachContentType() {
        return attachContentType;
    }

    public void setAttachContentType(String attachContentType) {
        this.attachContentType = attachContentType;
    }

    public String getCom_code() {
        return com_code;
    }

    public void setCom_code(String com_code) {
        this.com_code = com_code;
    }

    public String getCom_link_person() {
        return com_link_person;
    }

    public void setCom_link_person(String com_link_person) {
        this.com_link_person = com_link_person;
    }

    public String getCom_link_phone() {
        return com_link_phone;
    }

    public void setCom_link_phone(String com_link_phone) {
        this.com_link_phone = com_link_phone;
    }

    public String getCustoms_broker() {
        return customs_broker;
    }

    public void setCustoms_broker(String customs_broker) {
        this.customs_broker = customs_broker;
    }

    public String getCom_email() {
        return com_email;
    }

    public void setCom_email(String com_email) {
        this.com_email = com_email;
    }

    public String getCustoms_broker_id() {
        return customs_broker_id;
    }

    public void setCustoms_broker_id(String customs_broker_id) {
        this.customs_broker_id = customs_broker_id;
    }

    public String getCom_type() {
        return com_type;
    }

    public void setCom_type(String com_type) {
        this.com_type = com_type;
    }

    public String getCom_customs_code() {
        return com_customs_code;
    }

    public void setCom_customs_code(String com_customs_code) {
        this.com_customs_code = com_customs_code;
    }

    public String getService_port() {
        return service_port;
    }

    public void setService_port(String service_port) {
        this.service_port = service_port;
    }

    public String getService_port_code() {
        return service_port_code;
    }

    public void setService_port_code(String service_port_code) {
        this.service_port_code = service_port_code;
    }

}
